package com.gyhy.dumplings.order.interceptor;

import com.alibaba.fastjson.JSON;
import com.gyhy.dumplings.common.utils.JwtUtils;
import com.gyhy.dumplings.common.vo.MemberResponseVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.security.SignatureException;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description:
 * @author: 光影灰翼
 * @date: 2022-09-24 20:51
 * @version: 1.0
 * @email: 978330688@qq.com
 */
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    public static ThreadLocal<MemberResponseVo> toThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        String JWT = request.getHeader("token");
        try {
            // 1.校验JWT字符串
            Jws<Claims> claimsJws = JwtUtils.decode(JWT);
            // 2.取出JWT字符串载荷中的随机token，从Redis中获取用户信息
            // String token = claimsJws.getSignature();
            String token = String.valueOf(claimsJws.getBody().get("id"));
            String info = (String) redisTemplate.opsForValue().get(token);
            System.out.println(JSON.parse(info));
            // 3.将获取的信息转化为对象，并存到redis中。
            MemberResponseVo memberResponseVo =JSON.parseObject(JSON.toJSONString(JSON.parse(info)), MemberResponseVo.class);
            toThreadLocal.set(memberResponseVo);


            return true;
        }catch (SignatureException e){
            System.out.println("无效签名");
            e.printStackTrace();
        }catch (ExpiredJwtException e){
            System.out.println("token已经过期");
            e.printStackTrace();
        }catch (JwtException e){
            System.out.println("其他JWT错误");
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
